package com.lanou3g.musicenjoy.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.adapter.SearchAdapter;
import com.lanou3g.musicenjoy.adapter.SearchingActivityGirdViewAdapter;
import com.lanou3g.musicenjoy.entity.NewestSearch;
import com.lanou3g.musicenjoy.entity.SearchSongEntity;
import com.lanou3g.musicenjoy.entity.SongSearch;
import com.lanou3g.musicenjoy.volley.VolleySingleton;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 辛鑫 on 15/10/20.
 * 搜索界面
 */
public class SearchingMainFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView searchBack;
    private EditText searchInput;
    private ImageView searchImg;
    private GridView searchGridView;
    private ListView searchListView;
    private RequestQueue requestQueue;
    private List<NewestSearch.DataEntity> data;
    private SearchingActivityGirdViewAdapter adapter;
    private SearchingContentFragment fragment;
    private LinearLayout grid_liner;
    private ArrayList<SearchSongEntity> entity;
    private ListView serch_listView;
    private SearchAdapter searchAdapter;
    private Handler mHandler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.searching_layout, null);
        searchBack = (ImageView) view.findViewById(R.id.search_back);
        searchInput = (EditText) view.findViewById(R.id.search_input);
        searchImg = (ImageView) view.findViewById(R.id.search_img);
        searchGridView = (GridView) view.findViewById(R.id.search_gridView);
        grid_liner = (LinearLayout) view.findViewById(R.id.grid_liner);
        serch_listView = (ListView) view.findViewById(R.id.serch_listView);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mHandler = new Handler();
        searchBack.setOnClickListener(this);
        searchImg.setOnClickListener(this);
        searchGridView.setOnItemClickListener(this);
        requestQueue = VolleySingleton.getInstance(getActivity()).getRequestQueue();
        serch_listView.setOnItemClickListener(this);
        adapter = new SearchingActivityGirdViewAdapter(getActivity());
        getInternetData();
        TextChanged();
    }


    //文本改变方法
    public void TextChanged() {
        searchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    serch_listView.setVisibility(View.GONE);
                    grid_liner.setVisibility(View.VISIBLE);
                } else {
                    grid_liner.setVisibility(View.GONE);
                    serch_listView.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

                //开启线程
                mHandler.post(runnable);

            }
        });
    }

    //利用线程实现界面更新
    Runnable runnable = new Runnable() {
        String url;

        @Override
        public void run() {
            //获取数据
            final String datas = searchInput.getText().toString();
            //转为utf_8
            try {
                String songUrl = URLEncoder.encode(datas, "UTF-8");
                //网址拼接
                url = " http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&" +
                        "method=baidu.ting.search.catalogSug&format=json&query=" +
                        songUrl;

                //网络请求
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    //获取数据
                    entity = songSearch.getSong();
                    searchAdapter = new SearchAdapter(getActivity(), entity);
                    serch_listView.setAdapter(searchAdapter);

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            requestQueue.add(request);

        }
    };


    //从网络上拉取热门搜索的数据
    private void getInternetData() {
        String url = "http://api.dongting.com/misc/sug/billboard?uid=866058021842951" +
                "&f=f3040&v=v8.2.0.2015091720&app=ttpod&utdid=VSeGyjss0fEDAOqIktP5W%2" +
                "BO4&hid=1135212123029932&s=s200&alf=alf203200&imsi=460078098497828&tid=" +
                "0&net=2&size=20";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                NewestSearch entity = gson.fromJson(s, NewestSearch.class);
                if (entity != null && entity.getData() != null) {
                    data = entity.getData();
                    adapter.setDatas(data);
                    searchGridView.setAdapter(adapter);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        requestQueue.add(request);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_back:
                getFragmentManager()
                        .popBackStack();
                break;
            case R.id.search_img:
                String songName = searchInput.getText().toString();
                Log.i("xinxin", songName + "TTTT");
                if (songName.trim().length() <= 0) {
                    Toast.makeText(getActivity(), "请输入相关内容", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String str = URLEncoder.encode(songName, "UTF-8");
                        Bundle bundle = new Bundle();
                        bundle.putString("url", str);
                        fragment = new SearchingContentFragment();
                        fragment.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .replace(R.id.container, fragment)
                                .addToBackStack(null)
                                .commit();

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i("xixiixnxin", "点了了");
        switch (parent.getId()) {
            case R.id.search_gridView:
                Log.i("ttttt", "点击了gridView");
                TextView text = (TextView) view.findViewById(R.id.search_grid_text);
                String string = text.getText().toString();
                try {

                    String str = URLEncoder.encode(string, "UTF-8");
                    Bundle bundle = new Bundle();
                    bundle.putString("url", str);
                    fragment = new SearchingContentFragment();

                    fragment.setArguments(bundle);
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.container, fragment)
                            .commit();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.serch_listView:
                Log.i("ttttt", "点击了listView");
                TextView list_text = (TextView) view.findViewById(R.id.searchSongName);
                String stringOne = list_text.getText().toString();
                try {

                    String strOne = URLEncoder.encode(stringOne, "UTF-8");
                    Bundle bundle = new Bundle();
                    bundle.putString("url", strOne);
                    fragment = new SearchingContentFragment();
                    fragment.setArguments(bundle);
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.container, fragment)
                            .commit();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
        }



    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getFragmentManager()
                .beginTransaction()
                .remove(SearchingMainFragment.this)
                .commit();
    }
}
